.include "2313def.inc"

.def temp        = r16
.def temp2       = r17
.def ledStatus   = r18
.def buttonState = r19

	ldi  temp, low(RAMEND)
	out  SPL, temp			; init Stackpointer

	ldi  temp, 0xFF
	out  DDRB, temp	; set Port B to output
	
	ldi  temp, 0x00
	out  DDRD, temp	; set Port D to input
	
	ldi  temp, 0xFF
	out  PORTD, temp	; set Pull-Ups for port D
	
	ldi  temp, 0x00
	out  PORTB, temp	; set all pins of Port B to 0
	
	ldi  ledStatus, 0x00		; init ledStatus (LED Off)
	
loop:
	out  PORTB, ledStatus	; write ledStatus to Port B
	
	sbis PIND, 0
	rjmp buttonPressed
; if Button not pressed
	cpi  buttonState, 0xFF
	brne notPressedEnd
;     if button was pressed before
		  ;rcall toggle
		  rcall wait
;     fi
notPressedEnd:
	ldi  buttonState, 0x00		; set buttonState to released
	rjmp loop
;     continue
; else	
buttonPressed:
	cpi  buttonState, 0x00
	brne pressedEnd
;     if button was not pressed before
		  rcall toggle
		  rcall wait
;     fi
pressedEnd:
	ldi buttonState, 0xFF		; set buttonState to pressed
	rjmp loop
; fi


toggle:
	cpi  ledStatus, 0xFF
	brne switchOn
; if led is on
	ldi  ledStatus, 0x00			; switch it off
	rjmp endOfToggle
; else
switchOn:
	ldi  ledStatus, 0xFF			; switch it on
; fi
endOfToggle:
	ret
	
	
wait:
	ldi  temp2, 0x00
outerWaitLoop:
	ldi  temp, 0x00
	inc  temp2
innerWaitLoop:
	inc  temp
	cpi  temp, 0x00
	brne innerWaitLoop
	cpi  temp2, 0x00
	brne outerWaitLoop
	ret
